package algorithm.tree.binarytree.bfs;

import algorithm.tree.binarytree.base.TreeNode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class TreeNodeBFS {
    public static void traverse(TreeNode node, Consumer<TreeNode> consumer) {
        if (node != null) {
            traverse(List.of(node), consumer);
        }
    }

    private static void traverse(List<TreeNode> layerNodeList, Consumer<TreeNode> consumer) {
        List<TreeNode> nextLayerNodeList = new ArrayList<>();
        for (int i = 0; i < layerNodeList.size(); i++) {
            TreeNode currentNode = layerNodeList.get(i);
            consumer.accept(currentNode);
            if (currentNode.getLeft() != null) {
                nextLayerNodeList.add(currentNode.getLeft());
            }
            if (currentNode.getRight() != null) {
                nextLayerNodeList.add(currentNode.getRight());
            }
        }
        if (nextLayerNodeList.size() > 0) {
            traverse(nextLayerNodeList, consumer);
        }
    }

}
